/**
 * Created by on 2017/4/28.
 */
import axios from 'axios'
import router from '../router/index'

import Vue from 'vue'
import  {ToastPlugin} from 'vux'
Vue.use(ToastPlugin)

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.timeout = 3000

if(process.env.NODE_ENV === 'production'){
  //生产环境部署 http://101.37.179.214
  axios.defaults.baseURL = 'http://101.37.179.214'
}else if(process.env.NODE_ENV === 'test'){
  //测试环境部署 http://106.14.44.87:8886
  axios.defaults.baseURL = 'http://106.14.44.87:8886'
}else if(process.env.NODE_ENV === 'development'){
  //开发环境部署
  axios.defaults.baseURL = 'http://106.14.44.87:8886'
}else{
  console.info(process.env.NODE_ENV)
}
//请求拦截
axios.interceptors.request.use((config) => {
  //sessionStorage.getItem("parameter")
  let obj = sessionStorage.getItem("parameter")
  let token = JSON.parse(obj).token
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, (error) => {
  alert("参数错误");
  return Promise.reject(error)
})

//响应拦截
axios.interceptors.response.use((response) => {
  let resMeta = response.data.meta
  if (resMeta.code == 'SUCCESS') {
    return response
  } else if(resMeta.code == 'EXPIRED') {
    sessionStorage.setItem("errorMsg", resMeta.message);
    if (sessionStorage.getItem("errorMsg")) {
      router.replace({
        path: '/error',
      })
    }
  }else {
    Vue.$vux.toast.show({
      text: resMeta.message,
      type: 'cancel'
    })
  }

}, (error) => {
  if (error.response) {
    let statusCode = error.response.status
    if(statusCode == 401) {
      sessionStorage.errorMsg = '身份未验证，请确认身份信息'
    } else if(statusCode == 404) {
      sessionStorage.errorMsg = '错误：404  暂未找到页面'
    } else if (statusCode >= 500 && statusCode <= 505) {
      sessionStorage.errorMsg = '服务器发生错误，请稍后再试'
    }
    router.replace({
      path: '/error',
    })
  }
  return Promise.reject(error.response.data)
})
export default axios
